---  modbus rtu 从机模式 协议9600,N addr=01H(默认)
module(..., package.seeall)
local tag = "MCGS"
local dtu, udtu, uid = {}, {},2
-- local d_t = { --测试数据 1磷化氢 2氧气 3 气温 4气湿 5 仓温 6舱湿
-- 01 01 00 01 00 02 EC 0B 读取两个开关量
-- 01 01 01 02 D0 49  返回一个字节
-- 01 03 00 01 00 04 15 C9 读取气体
-- 01 05 00 01 FF 00 DD FA 门禁开
-- 01 05 00 01 00 00 9C 0A 门禁关
-- 01 05 00 02 FF 00 2D FA 灯光开
-- 01 05 00 02 00 00 6C 0A 灯光关
-- local data = {
--     devices[1][3] or 0,  devices[1][4] or 0,devices[2][3] or 0,  devices[2][4] or 0,
--     devices[3][3] or 0,  devices[3][4] or 0,devices[4][3] or 0,  devices[4][4] or 0,
--    }
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    sys.subscribe("USRDATA_UPDATE", flush)
    sys.taskInit(init)
end
local function getQC()
    local status = 0;
    for i = 1, 7 do
        status=status+(power.GET_QC(i) or 0)*(2^(i-1))
    end
    if status>0 then power.SET_QC(8,1) else  power.SET_QC(8,0) end
    return status
end
local function GET_DI()
    for i = 1, 8 do
        modbus_slave.REG_T[4][i]=1-power.GET_DI(i)
    end
end
local function flush_reg1()
    modbus_slave.REG_T[1][1]=getQC()
    GET_DI() --注册输入寄存器
end
function flush()
    local data = usrdata.getVal() or {}
    data = data.val or {}
    log.info("flush data:",data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8],data[9])
    local q1 = pack.pack(">f",data[1] or 0) 
    local q2 =  pack.pack(">f",data[3] or 0)
    local t1wd =  pack.pack(">f",data[5] or 0)
    local t1sd =  pack.pack(">f",data[6] or 0)
    local t2wd =  pack.pack(">f",data[7] or 0)
    local t2sd =  pack.pack(">f",data[8] or 0)
    --log.info(tag,q1:toHex())
    local _,q1H,q1L = pack.unpack(q1,">HH")
    local _,q2H,q2L = pack.unpack(q2,">HH")
    local _,t1wdH,t1wdL = pack.unpack(t1wd,">HH")
    local _,t1sdH,t1sdL = pack.unpack(t1sd,">HH")
    local _,t2wdH,t2wdL = pack.unpack(t2wd,">HH")
    local _,t2sdH,t2sdL = pack.unpack(t2sd,">HH")
    --磷化氢
    modbus_slave.REG_T[0x03][1]= q1H
    modbus_slave.REG_T[0x03][2]= q1L
    --氧气
    modbus_slave.REG_T[0x03][3]= q2H
    modbus_slave.REG_T[0x03][4]= q2L
    --气温
    modbus_slave.REG_T[0x03][5]= t1wdH
    modbus_slave.REG_T[0x03][6]= t1wdL
    --气湿
    modbus_slave.REG_T[0x03][7]= t1sdH
    modbus_slave.REG_T[0x03][8]= t1sdL
    --气温
    modbus_slave.REG_T[0x03][9]= t2wdH
    modbus_slave.REG_T[0x03][10]= t2wdL
    --气湿
    modbus_slave.REG_T[0x03][11]= t2sdH
    modbus_slave.REG_T[0x03][12]= t2sdL
    --ecode
    modbus_slave.REG_T[0x03][13]= data[9] or 0
end
function init()
    while true do
        local _, d = sys.waitUntil("UART_READ_DONE_NEXT_"..uid)
        if d then
            flush_reg1()
            modbus_slave.modbus_read(d)
        end
    end
end
